<?php
use Common\Util\BaseData;function get_cover_img($img){
    if(empty($img)) return '';
    $site_url = 'http://' . strip_tags ( $_SERVER ['HTTP_HOST'] ) . __ROOT__;
    if(stripos($img,'http://')!==false || stripos($img,'https://')!==false){
        return $img;
    }else{
        return $site_url.$img;
    }
}


/**
 * 过滤用户输入的基本数据，防止script攻击
 *
 * @access      public
 * @return      string
 */
function cyz_compile_str($str)
{
    $arr = array('<' => '＜', '>' => '＞','"'=>'”',"'"=>'’');

    return strtr($str, $arr);
}

/**
 *  将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
 *
 * @access  public
 * @param   string       $str         待转换字串
 *
 * @return  string       $str         处理后字串
 */
function cyz_make_semiangle($str)
{
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
        '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
        'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
        'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
        'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
        'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
        'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
        'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
        'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
        'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
        'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
        'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
        'ｙ' => 'y', 'ｚ' => 'z',
        '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
        '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
        '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
        '》' => '>',
        '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
        '：' => ':', '。' => '.', '、' => ',', '，' => ',', '、' => '.',
        '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
        '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
        '　' => ' ');

    return strtr($str, $arr);
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}
/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL,$format='Y-m-d H:i'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

/**
 * 系统非常规MD5加密方法
 * @param string $str 要加密的字符串
 * @param string $key
 * @return string
 */
function think_weiphp_md5( $str , $key = '' ) {
    empty ( $key ) && $key = C( 'AUTHCODE' );
    return '' === $str ? '' : md5( sha1( $str ) . $key );
}
/**
 * 密码加密
 */
function pass_md5($password){
	return md5($password.C('AUTHCODE'));
}

 /**
  * 手机号码验证
  */
function isMobile($str){
    $exp = "/^1[3|4|5|6|7|8|9][0-9]{9}$/";
    if(preg_match($exp,$str)){
        return true;
    }else{
        return false;
    }
}


/*验证传参ID*/
function checkSqlID($id){
    if($id < 0 || !is_numeric($id) || !isset($id)){
        return false;
    }
    return true;
}

/**
 * 获取文件md5
 * @param string $file_name
 * @param string $type
 * @return string
 */
function get_file_hash($file_name = '' ,$type = 'sha1')
{
    return  hash_file($type, $file_name);
}
/**
 * 格式化价格
 * @param $str
 * @return string
 */
function formatPrice($str){
    return sprintf("%.2f",$str);
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author rainfer <81818832@qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB', ' PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}
/**
 * 清除缓存
 * @author rainfer <872086222@qq.com>
 */
function clear_cache(){
    remove_dir(TEMP_PATH);
    remove_dir(CACHE_PATH);
    remove_dir(DATA_PATH);
    remove_dir(LOG_PATH);
    file_exists($file = RUNTIME_PATH . 'common~runtime.php') && @unlink($file);
}
/**
 * 列出本地目录的文件
 * @author rainfer <872086222@qq.com>
 *
 * @param string $filename
 * @param string $pattern
 * @return Array
 */
function list_file($filename, $pattern = '*')
{
    if (strpos($pattern, '|') !== false) {
        $patterns = explode('|', $pattern);
    } else {
        $patterns [0] = $pattern;
    }
    $i = 0;
    $dir = array();
    if (is_dir($filename)) {
        $filename = rtrim($filename, '/') . '/';
    }
    foreach ($patterns as $pattern) {
        $list = glob($filename . $pattern);
        if ($list !== false) {
            foreach ($list as $file) {
                $dir [$i] ['filename'] = basename($file);
                $dir [$i] ['path'] = dirname($file);
                $dir [$i] ['pathname'] = realpath($file);
                $dir [$i] ['owner'] = fileowner($file);
                $dir [$i] ['perms'] = substr(base_convert(fileperms($file), 10, 8), -4);
                $dir [$i] ['atime'] = fileatime($file);
                $dir [$i] ['ctime'] = filectime($file);
                $dir [$i] ['mtime'] = filemtime($file);
                $dir [$i] ['size'] = filesize($file);
                $dir [$i] ['type'] = filetype($file);
                $dir [$i] ['ext'] = is_file($file) ? strtolower(substr(strrchr(basename($file), '.'), 1)) : '';
                $dir [$i] ['isDir'] = is_dir($file);
                $dir [$i] ['isFile'] = is_file($file);
                $dir [$i] ['isLink'] = is_link($file);
                $dir [$i] ['isReadable'] = is_readable($file);
                $dir [$i] ['isWritable'] = is_writable($file);
                $i++;
            }
        }
    }
    $cmp_func = create_function('$a,$b', '
		if( ($a["isDir"] && $b["isDir"]) || (!$a["isDir"] && !$b["isDir"]) ){
			return  $a["filename"]>$b["filename"]?1:-1;
		}else{
			if($a["isDir"]){
				return -1;
			}else if($b["isDir"]){
				return 1;
			}
			if($a["filename"]  ==  $b["filename"])  return  0;
			return  $a["filename"]>$b["filename"]?-1:1;
		}
		');
    usort($dir, $cmp_func);
    return $dir;
}
/**
 * 删除文件夹
 * @author rainfer <872086222@qq.com>
 *
 */
function remove_dir($dir, $time_thres = -1)
{
    foreach (list_file($dir) as $f) {
        if ($f ['isDir']) {
            remove_dir($f ['pathname'] . '/');
        } else if ($f ['isFile'] && $f ['filename'] != C('DIR_SECURE_FILENAME')) {
            if ($time_thres == -1 || $f ['mtime'] < $time_thres) {
                @unlink($f ['pathname']);
            }
        }
    }
}

function hx_write_app_log($poststr,$file){//写入日志方法
    $fp = fopen(RUNTIME_PATH.$file.'-'.date("Y_m_d").".txt","a");
    flock($fp, LOCK_EX);
    fwrite($fp,"执行日期：".strftime("%Y-%m-%d %H:%M:%S",time())."\n".$poststr."\n"."请求IP：".$_SERVER["REMOTE_ADDR"]."\n"."请求地址：".__SELF__."\n\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

function cyz_curl_get_contents($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}


//发送http请求,返回json数据
function cyz_curl_post_contents($url, $data = null){
    $curl = curl_init();
    //设置超时
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    //设置header
    curl_setopt($curl, CURLOPT_HEADER, FALSE);
    //要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

function http_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data))
    {
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data))
        );
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/*获取微信TOKEN*/
function cyz_getWxToken($appid,$appsecret){
    $access_token_s = S('access_token_apppid_' . $appid . '_' . $appsecret);
    if($access_token_s){
        $access_token_arr = json_decode($access_token_s,true);
        $timenow = time();
        if($timenow > $access_token_arr['endtime']){
            return cyz_getNewToken($appid,$appsecret);
        }else{
            return $access_token_arr['access_token'];
        }
    }else{
        return cyz_getNewToken($appid,$appsecret);
    }
}
/*生成新的TOKEN*/
function cyz_getNewToken($appid,$appsecret){
    $access_token_s = 'access_token_apppid_' . $appid . '_' . $appsecret;
    $token_get_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
    $get_token = cyz_curl_get_contents($token_get_url);
    $get_token = json_decode($get_token,true);
    if($get_token['access_token']){
        $get_token['endtime'] = time() + $get_token['expires_in'] - 600;
        $get_token_str = json_encode($get_token);
        S($access_token_s,$get_token_str,$get_token['expires_in'] - 300);
        return $get_token['access_token'];
    }else{
        return false;
    }
}

function https_request($url, $data = null)
	{
		$curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_URL, $url);

		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);

			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

		}

		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

		$output = curl_exec($curl);

		curl_close($curl);

		return $output;

	}


	/**
	 * 获取access_token
	 *
	 * @return void
	 */

function get_access_token(){
		$appSetting = BaseData::getAppSetting();
		$appID = $appSetting['wechat_appid'];
		$appsecret = $appSetting['wechat_appsecret'];
        (new \Common\Model\Log\LogModel())->addLog(__FUNCTION__,['appid' => $appID,'secret' => $appsecret]);
		$get_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appID."&secret=".$appsecret;
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $get_url);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$data = curl_exec($curl);
		curl_close($curl);
		$token = json_decode($data);
		return ($token->access_token);
	}


function format_date($time){
    $t=time()-$time;
    $f=array(
        '31536000'=>'年',
        '2592000'=>'个月',
        '604800'=>'星期',
        '86400'=>'天',
        '3600'=>'小时',
        '60'=>'分钟',
        '1'=>'秒'
    );
    foreach ($f as $k=>$v)    {
        if (0 !=$c=floor($t/(int)$k)) {
            return $c.$v.'前';
        }
    }
}
/**
 * 记录行为日志，并执行该行为的规则(将废弃)
 * @param string $action 行为标识
 * @param string $model 触发行为的模型名
 * @param int $record_id 触发行为的记录id
 * @param int $user_id 执行行为的用户id
 * @deprecated
 * @return boolean
 * @author huajie <banhuajie@163.com>
 */
function action_log($action = '', $model = '', $record_id = '', $user_id = 0,$user_name='',$remark=''){

    //参数检查
//    if(empty($action) || empty($model) || empty($record_id)){
//        return '参数不能为空';
//    }

    //插入行为日志
    $data['action_name']    =   $action?$action:'';
    $data['user_id']        =   $user_id?$user_id:'';
    $data['user_name']      =   $user_name?$user_name:'';
    $data['action_ip']      =   get_client_ip(0);
    $data['model']          =   $model?$model:'';
    $data['record_id']      =   $record_id?$record_id:'';
    $data['create_time']    =   NOW_TIME;
    $data['remark']     =   $remark?$remark:'操作url：'.$_SERVER['REQUEST_URI'];
    M('ActionLog')->add($data);
}

/**
 * 获取数组中的某一项，并给个默认值
 * @param $arr
 * @param $key
 * @param $default
 * @return mixed|string
 */
//function arr_get($arr,$key,$default=''){
//    if(isset($arr[$key])){
//        return $arr[$key];
//    }
//    return $default;
//}
/**
 * 安全获取数组中指定路径的值，支持多级嵌套
 *
 * @param array $arr 要检索的数组
 * @param string|array $key 键名或键路径（如 'a.b.c' 或 ['a', 'b', 'c']）
 * @param mixed $default 默认值（未找到时返回）
 * @return mixed 指定路径的值或默认值
 */
function arr_get($arr, $key, $default = '')
{
    // 如果键为空，直接返回原数组
//    if (empty($key)) {
//        return $arr;
//    }

    // 将点号分隔的键转换为数组路径
    $keys = is_array($key) ? $key : explode('.', $key);

    // 逐级访问数组
    $current = $arr;
    foreach ($keys as $segment) {
        // 检查当前层级是否存在且为数组
        if (!is_array($current) || !array_key_exists($segment, $current)) {
            return $default;
        }
        $current = $current[$segment];
    }

    return $current;
}

/**
 * @param $content
 * @return void
 */
function bin_dump($content){
    dump($content);
    die();
}

function format_exception(\Exception $e, array $appends = []): array
{
    return array_merge([
        'code' => $e->getCode(),
        'msg' => $e->getMessage() ?? '',
        'file' => $e->getFile() . ':' . $e->getLine(),
        'trace' => array_slice($e->getTrace(), 0, 5)
    ], $appends);
}

function get_oss_config()
{
    return C('UPLOAD_QINIU_CONFIG');
}

function get_url_path($url) {
    $parsedUrl = parse_url($url);
    if (isset($parsedUrl['path'])) {
        return $parsedUrl['path'];
    }
    return '';
}

function extract_path_from_url($url): string
{
    if (empty($url)) {
        return '';
    }
    if (str_starts_with($url, 'http://') || str_starts_with($url, 'https://')) {
        $url = sprintf('/%s',ltrim(parse_url($url, PHP_URL_PATH),'/'));
    }
    return $url;
}

/**
 * 获取当前时间 年月日格式
 * @return false|string
 */
function get_now_date()
{
    return date('Y-m-d H:i:s');
}

function strtodate($timestamp){
    return date('Y-m-d H:i:s',$timestamp);
}

/**
 * 计算两个时间戳之间间隔的天数
 * @param int $timestamp1 第一个时间戳
 * @param int $timestamp2 第二个时间戳
 * @return int 间隔的天数
 */
function calculate_days_difference($timestamp1, $timestamp2) {
    // 计算两个时间戳的差值（以秒为单位）
    $difference = abs($timestamp1 - $timestamp2);
    // 将差值转换为天数
    $days = floor($difference / (60 * 60 * 24));
    return $days;
}

/**
 * 生成指定位数的随机字符
 * @param $length
 * @return string
 */
function generate_random_string($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString.= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

/**
 * post参数获取
 * @return mixed
 */
function post_params(){
    $params = file_get_contents('php://input');
    $params = json_decode($params,true);
    return $params;
}
?>
